import { request } from '../../request/index'
import TimeShow from '../../utils/TimeShow'
var { formatTime } = require('../../utils/Time')
//消息协议
var SocketMessage = require('../../utils/SocketMessage')
var timeUtil = require('../../utils/Time')
import getUserInfo from '../../utils/getUserInfo'
Page({
  data: {
    user: {},
    num: [],
    followed: false,
    chatid: null,
    userId: null,
    showType: 1,
    isXiaLa: false
  },
  userInfo: wx.getStorageSync('userInfo'),
  curentPage: 1,

  onLoad: function (options) {
    const { userId } = options
    this.getInfo([userId])
    console.log(userId)
    // 当前人id
    if (userId) {
      this.setData(
        {
          userId: wx.getStorageSync('userId'),
          chatid: userId
        },
        () => {
          this.checkGuan(this.data.userId, this.data.chatid)
          this.getUserInfo(this.data.chatid, this.data.showType, 1)
        }
      )
    }
    this.getUser()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.getUserInfo(this.data.chatid, this.data.showType, 1)
    this.curentPage = 1
    this.setData({
      isXiaLa: false
    })
  },
  onReachBottom() {
    this.curentPage += 1
    this.getUserInfo(this.data.chatid, this.data.showType, this.curentPage)
  },

  getUser() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({
        userInfo
      })
    }
  },
  // 发布按钮
  handFa() {
    wx.switchTab({
      url: '/pages/create/create',
      fail: (e) => {
        console.log('跳转失败' + e)
      }
    })
  },
  // 点赞
  async handChang(e) {
    const { id } = e.currentTarget.dataset
    let dian = wx.getStorageSync('dian')
    if (!dian) dian = []
    let { num } = this.data
    let userid = null
    const dianData = {
      postId: id,
      uId: this.data.userId,
      cTime: formatTime(new Date())
    }
    const { data } = await request({
      url: `/like/${JSON.stringify(dianData)}/${this.data.showType}`,
      method: 'post'
    })
    console.log(data)
    if (data.state == 1) {
      num.some((item) => {
        if (item.id === id) {
          item.isClick = true
          item.likeNum += 1
          userid = item.userid
          return true
        }
      })

      dian.push(id)
      wx.setStorageSync('dian', dian)
      const dainData = {
        userId: this.data.userId,
        chatId: this.data.chatid,
        message: `${this.userInfo.nickName}赞了你`,
        messageType: SocketMessage.GREAT,
        stime: timeUtil.formatTime(new Date())
      }
      wx.sendSocketMessage({
        data: JSON.stringify(dainData)
      })
    }
    if (data.state == 2) {
      num.some((item) => {
        if (item.id === id) {
          item.isClick = false
          item.likeNum -= 1
          return true
        }
      })
      dian.some((item, i) => {
        if (item == id) {
          dian.splice(i, 1)
          return true
        }
      })
      wx.setStorageSync('dian', dian)
    }
    this.setData({
      num
    })
  },
  // 关注按钮
  async handGuan() {
    if (this.data.followed) {
      wx.showModal({
        title: '提示',
        content: '确定取消关注?',
        success: async (res) => {
          if (res.confirm) {
            const { data } = await request({
              url: `/excelfollowSb/${this.data.userId}/${this.data.chatid}`,
              method: 'post'
            })
            if (data.state === 1) {
              this.setData({
                followed: false
              })
              wx.showToast({
                title: '成功取消关注',
                icon: 'success',
                duration: 1500
              })
            }
          } else if (res.cancel) {
            return
          }
        }
      })
    } else {
      const { data } = await request({
        url: `/followSb/${this.data.userId}/${this.data.chatid}`,
        method: 'post'
      })
      if (data.state === 1) {
        this.setData({
          followed: true
        })
        wx.showToast({
          title: '关注成功',
          icon: 'success',
          duration: 1500
        })
      }
    }
  },

  // 动态详情页
  HandXiangQiang(e) {
    const { id } = e.currentTarget.dataset
    let { num } = this.data
    let don = null
    num.some((item) => {
      if (item.id === id) {
        don = item
        return true
      }
    })
    wx.navigateTo({
      url:
        '/pages/details/details?num=' +
        JSON.stringify(don) +
        '&type=' +
        this.data.showType
    })
  },

  // 发消息
  handFaL(e) {
    const { chatid, username } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/demes/demes?chatId=${chatid}&username=${username}`
    })
  },
  // 墙
  handXUanType(e) {
    const { type } = e.currentTarget.dataset
    this.setData({
      showType: type
    })
    this.getUserInfo(this.data.chatid, type, 1)
  },

  // 获得个人信息墙
  async getUserInfo(uid, type, curPage) {
    const { data } = await request({
      url: `/selfposts/${uid}/${type}/${curPage}`,
      method: 'post'
    })
    if (data.state == -2) {
      wx.stopPullDownRefresh()
      wx.showToast({
        title: '刷新太快了哦',
        icon: 'error',
        duration: 2000
      })
      return
    }
    if (data.state == 0) {
      wx.showToast({
        title: '出错了',
        icon: 'error',
        duration: 2000
      })
      return
    }
    let nums = this.data.num
    if (curPage === 1) nums = []
    let num = data.data
    if (num.length <= 0) {
      this.curentPage -= 1
      wx.showToast({
        title: '没有了哦',
        icon: 'error',
        duration: 2000
      })
      // return
    }
    let dian = wx.getStorageSync('dian')
    if (!dian) dian = []
    num.forEach((item) => {
      if (dian.includes(item.id)) {
        item['isClick'] = true
      } else {
        item['isClick'] = false
      }
      const paths = item.imgPath
      const as = paths.trim().split('|')
      if (!item['imgs']) item['imgs'] = []
      as.forEach((value, index) => {
        if (index < as.length - 1) item['imgs'].push(value)
      })
      const times = item['ctime'].split('-')
      item['month'] = times[1] + '月'
      item['day'] = times[2].split(' ')[0]
      item['ctime'] = TimeShow(item['ctime'])
      const { uheadpic } = item
      let headpic = ''
      const ss = uheadpic.split('xd728')
      ss.forEach((value) => {
        if (headpic === '') {
          headpic = value
        } else {
          headpic += `/${value}`
        }
      })
      item['uheadpic'] = headpic
    })
    if (curPage != 1) {
      nums = [...nums, ...num]
      this.setData({
        num: nums
      })
    } else {
      this.setData({
        num,
      })
    }
  },

  // 检查是否关注
  async checkGuan(myid, uid) {
    // if(myid === uid) return
    const { data } = await request({
      url: `/checkfollow/${myid}/${uid}`,
      method: 'post'
    })
    this.setData({
      followed: data.followed
    })
  },

  async getInfo(ids) {
    const uInfo = await getUserInfo(ids)
    this.setData({
      uInfo: uInfo[0]
    })
  }
})
